package cn.edu.dz.bank1;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 同步块的使用，可以一人用一把锁
 */

public class Bank1 {
    //属性：账户余额100元
    private int account=100;

    //private Object lock_ask=new Object();
    //private Object lock_getMoney=new Object();
    private final ReentrantLock lock = new ReentrantLock();
    public  void ask() {
        this.lock.lock();
            //咨询方法
        try {
            System.out.println(Thread.currentThread().getName() + "向大堂经理咨询业务");
            try {
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + "咨询结束");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }finally { this.lock.unlock();
        }
    }

    //方法：取钱
    public int  getMoney(int order){
                this.lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "正在取款。。。。。。。。。。。");

                    //当账户余额大于所需要取款的金额
                    if (account >= order) {
                        //正常取款
                        System.out.println("系统正在处理。。。。。。");
                        //Math方法，产生随机数
                        long m = (long) (Math.random() * 2000 + 600);
                        try {
                            //线程休眠，模拟取款等待时间
//                Thread.sleep(m);
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //当前账户余额为账户金额-取款金额
                        account -= order;
                        //输出提示语句
                        System.out.println("尊敬的" + Thread.currentThread().getName() + "用户，您本次的取款金额是：" + order + "元，" +
                                "当前账户余额为" + account + "元");
                        return order;
                    } else {
                        //当账户余额小于所需取款的金额，提示，操作失败
                        System.out.println("对不起，操作失败，余额不足。。。。。");
                        return 0;
                    }
                }finally{
                    this.lock.unlock();
                }




        }


    }


